const express = require('express');
const router = express.Router();
const { Course, Category, User } = require('../../models');
const { success, failure } = require('../../utils/responses');

/**
 * 查询首页数据
 * GET /
 */
router.get('/', async function (req, res, next) {
  try {
    const recommended = await Course.findAll({
      attributes: { exclude: ['CategoryId', 'UserId', 'content'] },
      where: { recommended: true },
      order: [['id', 'desc']],
      limit: 10,
      include: [
        {
          model: Category,
          as: 'category',
          attributes: ['id', 'name'],
        },
        {
          model: User,
          as: 'user',
          attributes: ['id', 'username'],
        },
      ],
    });
    const likes = await Course.findAll({
      order: [['likesCount', 'desc']],
      attributes: { exclude: ['CategoryId', 'UserId', 'content'] },
      limit: 10,
    });
    const introductory = await Course.findAll({
      attributes: {
        exclude: ['CategoryId', 'UserId', 'content'],
      },
      order: [['id', 'desc']],
      where: { introductory: true },
      limit: 10,
    });
    success({ res, data: { recommended, likes, introductory } });
  } catch (error) {
    failure({ res, error });
  }
});

module.exports = router;
